package com.example.sxproject.controller;

import com.example.sxproject.pojo.*;
import com.example.sxproject.service.RecipientService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/recipient")
public class RecipientController {

    @Autowired
    private RecipientService recipientService;

    //查询：根据所属用户查询
    @GetMapping("/selectByUserId")
    public Result selectByUserId(@RequestParam Integer userId) {
        List<Recipient> recipients = recipientService.selectByUserId(userId);
        return Result.success(recipients);
    }

    //添加：添加一个收款人
    @RequestMapping("/addRecipient")
    public String addRecipient(Recipient recipient, HttpSession session) {
        Integer userId = (Integer) recipient.getUserId();
        User user = (User) session.getAttribute("user");
        if(userId == null || userId == 0) {
            recipient.setUserId(user.getId());
        }
        recipientService.addRecipient(recipient);
        List<Recipient> recipients = recipientService.selectByUserId(user.getId());
        session.setAttribute("recipients", recipients);
        return "recipientList";
    }

    //更新：更新收款人信息
    @PutMapping("/updateRecipient")
    public Result updateRecipient(@RequestBody @Validated Recipient recipient) {
        recipientService.updateRecipient(recipient);
        return Result.success();
    }


    //更新：假删除
    @PutMapping("/delete")
    public Result delete(@RequestBody @Validated Recipient recipient) {
        recipient.setStatus(2);
        recipientService.delete(recipient);
        return Result.success();
    }


}
